<?php
class Model_Sessions extends Model
{
	// Save a session
	public static function save($id, $username, $level, $expiration_date)
	{
		DB::insert('sessions')->set(array(
			'id' 			  => $id,
			'username'        => $username,
			'level' 		  => $level,
			'expiration_date' => $expiration_date,
		))->execute();
	}
		
	// Update sessions' expiration
	public static function update($id)
	{
		$results = DB::select('id', 'expiration_date')
			->from('sessions')->execute()->as_array();
		
		for ($counter = 0; $counter < count($results); $counter++)
		{
			$timestamp = Date::time('Asia/Manila')->get_timestamp();
			$current = Date::forge($timestamp, 'Asia/Manila')->format('mysql');
		
			if ($results[$counter]['id'] == $id)
			{
				if ($current >= $results[$counter]['expiration_date'])
				{
					DB::delete('sessions')
						->where('id', $id)
							->execute();
					
					continue;
				}
			
				$timestamp += (60 * 30);
				$current = Date::forge($timestamp, 'Asia/Manila')->format('mysql');
				
				DB::update('sessions')
					->value('expiration_date', $current)
						->where('id', $id)
							->execute();
				continue;
			}
			
			if ($current >= $results[$counter]['expiration_date'])
			{
				DB::delete('sessions')
					->where('id', $results[$counter]['id'])
						->execute();
			}
		}
	}
	
	// Determines if a certain user has an active session
	public static function contains($username)
	{
		$results = DB::select('username')
			->from('sessions')->execute()->as_array();
		
		for ($counter = 0; $counter < count($results); $counter++)
		{
			if ($results[$counter]['username'] == $username)
			{
				return true;
			}
		}
		
		return false;
	}
	
	// Retrieves the level of a given session
	public static function level($session)
	{
		$results = DB::select('id', 'level')
			->from('sessions')->execute()->as_array();
		
		for ($counter = 0; $counter < count($results); $counter++)
		{
			if ($results[$counter]['id'] == $session)
			{
				return $results[$counter]['level'];
			}
		}
		
		return false;
	}
		
	// Generate a unique session id
	public static function generate_guid()
	{
		$hash = md5(uniqid(rand(), true)); 
		
		$guid = sprintf('%s-%s-%s-%s-%s',
						substr($hash, 0, 8),
						substr($hash, 8, 4),
						substr($hash, 12, 4), 
						substr($hash, 16, 4), 
						substr($hash, 20));
			
		return $guid;
	}

	// Retrieves the username of a given session
	public static function username($session)
	{
		$results = DB::select('id', 'username')
			->from('sessions')->execute()->as_array();
		
		for ($counter = 0; $counter < count($results); $counter++)
		{
			if ($results[$counter]['id'] == $session)
			{
				return $results[$counter]['username'];
			}
		}
		
		return false;
	}
}
?>